'use strict'

const {httpcli} = require('gohttp');

const wxkey = require('../config/wxkey.js');

class sllogin {

  constructor () {
    //param默认就是/:id，若要改变路由，则可以设置此属性，比如设置为/:name
    this.param = '/:code';
  }

  /**
   * 获取资源具体内容
   * @param {context} c
   * @returns 
   */
  async get (c) {
    let code = c.param.code;
    //使用queryString的形式拼接请求的url地址
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxkey.appid}&secret=${wxkey.secret}&js_code=${code}&grant_type=authorization_code`;
    let ret = await httpcli.get(url);
    
    if(!ret.ok) {
        return c.status(500).send('request failed!');
    }
    
    let r = ret.json();

    //设置需要返回的数据并且将数据进行加密
    let data = {
        openid:r.openid,
        login_time:Date.now()
    };

    c.send(c.helper.aesEncrypt(JSON.stringify(data),c.service.aeskey));
  }
}

module.exports = sllogin;

